package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	@Autowired
	private UserAccountService userAccountService;


	/**
	 * 根据订单号获取充值信息
	 *
	 * @param orderNo
	 * @return
	 */
	@Override
	public RechargeInfo getRechargeInfoByOrderNo(String orderNo) {
		LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
		return rechargeInfoMapper.selectOne(queryWrapper);
	}

	/**
	 * 处理充值成功消息
	 *
	 * @param orderNo
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rechargeSuccess(String orderNo) {
		//1.根据充值订单编号查询充值记录状态
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
		if (rechargeInfo != null && SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())) {
			//只处理未支付
			rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
			rechargeInfoMapper.updateById(rechargeInfo);
			//2.修改账户总金额、可用余额
			userAccountService.add(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());

			//3.新增账户变动记录
			userAccountService.saveUserAccountDetail(rechargeInfo.getUserId(), "充值", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), rechargeInfo.getOrderNo());
		}
	}
}
